/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.lundberg.podcasts.util;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Environment;

/**
 *
 * @author lundbergg
 */
public class Util
{
	public static final String CACHE_DIR = "Android/data/org.lundberg.podcasts";
	public static final SimpleDateFormat RFC822_DATE_FORMAT_1 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
	public static final SimpleDateFormat RFC822_DATE_FORMAT_2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
	public static final SimpleDateFormat ISO8601_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    
    
    
    
    /**
	 * Determines the age of the Item by its pubDate
	 * 
	 * @param item
	 * @return a string representation of the Item's age
	 */
    public static String getItemAge(String pubDate)
    {
        Calendar now = Calendar.getInstance();
        Calendar then = Calendar.getInstance();
        
        if (pubDate == null) {
        	return "";
        }
        
        try
        {
            then.setTime(Util.ISO8601_DATE_FORMAT.parse(pubDate));
        }
        catch(ParseException e) {
            e.printStackTrace();
        }

        long delta = now.getTimeInMillis() - then.getTimeInMillis();
        
        long seconds = delta / 1000;
        
        if (seconds < 60) {
        	
        	return seconds+ ((seconds == 1) ? " second" : " seconds") + " ago";
        }
        
        long minutes = seconds / 60;
        
        if (minutes < 60) {
        	
        	return minutes+ ((minutes == 1) ? " minute" : " minutes") + " ago";
        }
        
        long hours = minutes / 60;
        
        if (hours < 24) {
        	
        	return hours+ ((hours == 1) ? " hour" : " hours") + " ago";
        }
        
        long days = hours / 24;
        
        if (days < 7) {
        	
        	return days+ ((days == 1) ? " day" : " days") + " ago";
        }
        
        long weeks = days / 7;
        
        if (weeks < 4) {
        	
        	return weeks+ ((weeks == 1) ? " week" : " weeks") + " ago";
        }
        
        long months = weeks / 4;
        
        if (months < 12) {
        	
        	return months+ ((months == 1) ? " month" : " months") + " ago";
        }
        
        long years = months / 12;
        
        return years+ ((years == 1) ? " year" : " years") + " ago";
    }
    
    
    
    public static boolean isNetworkAvailable(Context context)
    {    	
    	final ConnectivityManager connMgr = (ConnectivityManager)
    			context.getSystemService(Context.CONNECTIVITY_SERVICE);

    	final android.net.NetworkInfo wifi =
    			connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    	if (wifi.isConnected()) {
    		
    		return true;
    	}
    	
    	final android.net.NetworkInfo mobile =
    			connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    	
    	return mobile.isConnected();
    }
    
    
    public static boolean isWiFiAvailable(Context context)
    {
    	final ConnectivityManager connMgr = (ConnectivityManager)
    			context.getSystemService(Context.CONNECTIVITY_SERVICE);

    	final android.net.NetworkInfo wifi =
    			connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    	return wifi.isConnected();
    }
    
    
    /**
     * isDownloaded version which doesn't compare file size.
     * Sometimes the data in the podcast xml is incorrect
     * or missing, so it's not worth the extra step.
     * 
     * @param guid the Item's GUID 
     * @return whether the podcast file exists
     */
    public static boolean isDownloaded(String guid)
    {
    	String filename = getPodcastFilename(guid);
    	File file = new File(filename);
    	
    	return file.exists();
    }
    
    
    /**
     * Utility method for determining the local cache directory
     * on the sdcard (i.e. '/sdcard/Android/data/org.lundberg.podcasts')
     * 
     * @return a File representing the cache directory
     */
    public static File getCacheDir()
    {
    	String sdRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
        File directory = new File(sdRoot+"/"+CACHE_DIR);

        if (!directory.exists()) {

        	directory.mkdirs();
        }
        
        return directory;
    }
    
    
    /**
     * Determines the filename of the Item.  The short filename is
     * simply the hashcode of the Item's guid in hexadecimal.
     * 
     * @param guid the GUID of the Item
     * @return the absolute filename of the podcast
     */
    public static String getPodcastFilename(String guid)
    {
    	return (guid == null) ? "" : getCacheDir() +"/item_"+String.format("%x", guid.hashCode());
    }
    
    
    /**
     * Determines the filename of the Item's icon.  The short filename is
     * simply the hashcode of the icon's URL in hexadecimal.
     * 
     * @param url the URL of the Item's icon
     * @return the absolute filename of the icon
     */
    public static String getIconFilename(String url)
    {
    	return getCacheDir() +"/"+String.format("%x", url.hashCode());
    }
    
    
    /**
     * Converts the specified time to a string representation in
     * H:MM:SS format.
     * 
     * @param milliseconds the time in milliseconds since the Epoch
     * @return a string representation of the time in H:MM:SS format
     */
    public static String timeIntToString(int milliseconds)
    {
    	long seconds = milliseconds/1000;
    	long hours = (seconds/3600);
    	seconds %= 3600;
    	
    	long minutes = (seconds/60);
    	seconds %= 60;
    	
    	return ((hours > 0) ? hours+":" : "")
				+((minutes < 10) ? "0"+minutes : minutes)+":"
				+((seconds < 10) ? "0"+seconds : seconds);
    }
    
    
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
	    
		// Raw height and width of image
	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int inSampleSize = 1;
	
	    if (height > reqHeight || width > reqWidth) {
	        if (width > height) {
	            inSampleSize = Math.round((float)height / (float)reqHeight);
	        } else {
	            inSampleSize = Math.round((float)width / (float)reqWidth);
	        }
	    }
	    
	    return inSampleSize;
	}
}
